import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
/**
 * 类型检查
 */

export function typeCheck(param: any) {
  return Object.prototype.toString.call(param);
}

export function formatDate(date: any) {
  const nowdate = new Date(date);
  const YY = nowdate.getFullYear() + '-';
  const MM = (nowdate.getMonth() + 1 < 10 ? '0' + (nowdate.getMonth() + 1) : nowdate.getMonth() + 1) + '-';
  const DD = (nowdate.getDate() < 10 ? '0' + (nowdate.getDate()) : nowdate.getDate());
  const hh = (nowdate.getHours() < 10 ? '0' + nowdate.getHours() : nowdate.getHours()) + ':';
  const mm = (nowdate.getMinutes() < 10 ? '0' + nowdate.getMinutes() : nowdate.getMinutes()) + ':';
  const ss = (nowdate.getSeconds() < 10 ? '0' + nowdate.getSeconds() : nowdate.getSeconds());
  return YY + MM + DD + " " + hh + mm + ss;
}
/*
检测是否是ios
*/
export function isIOS() {
  const u = navigator.userAgent;
  const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
  return isiOS;
}

//将base64转换为blob
export function dataURLtoBlob(dataurl: any) {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {
    type: mime
  });
}
//将blob转换为file
export function blobToFile(blob: AnyObject, fileName: string) {
  blob.lastModifiedDate = new Date();
  blob.name = fileName;
  return blob;
}

// 防抖 定时器实现（立即执行版本）
// export function debounce(fn: any, delay = 200) {
//   let timer = null as NodeJS.Timer | null
//   return function () {
//     const args = arguments
//     const now = !timer
//     timer && clearTimeout(timer)   //timer不为null时执行clearTimeout函数
//     timer = setTimeout(() => {
//       timer = null
//     }, delay)
//     if (now) {
//       fn.apply(this, args)
//     }  //或者：now && fn.apply(this, args)
//   }
// }
/**
 * @description 是否是移动端
 */
export function isMobile() {
  const userAgentInfo = navigator.userAgent;
  const Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
  const getArr = Agents.filter(i => userAgentInfo.includes(i));
  return getArr.length ? true : false;
}

/**
 * @description 防抖
 * @param func 需要包装的函数
 * @param delay 延迟时间，单位ms
 */
export function debounce(
  fn: any,
  delay = 200
) {
  let timer: NodeJS.Timer;
  return function () {
    if (timer) clearTimeout(timer);
    timer = setTimeout(function () {
      fn()
    }, delay)
  };
}
/**
 * @description 防抖
 * @param month 日期数组['2021', '01']
 */
export function dateFormatter(date: any[]) {
  return date ? (date.length == 1 ? date[0] : date[0] + "-" + date[1]) : undefined;
}

/**
 * @description 钉钉规则生成头像
 * @param name 姓名
 */
export function generateAvatarByName(name: string, size = 50, bg = "#0084ff") {
  if (!name) return;
  const sliceName = name.slice(-2)
  const max = 6;
  const canvas = document.createElement("canvas") as HTMLCanvasElement;
  const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
  canvas.width = canvas.height = max * size;
  ctx.fillStyle = bg;
  ctx.fillRect(0, 0, max * size, max * size);
  ctx.font = 16 * max + "px Arial";
  ctx.fillStyle = "#fff";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillText(sliceName, max * size / 2, max * size / 2)
  return canvas.toDataURL("image/png", 1);
}
/**
 * @description 钉钉重定向链接
 * @param name 姓名
 */
export function dingdingLinkOpen() {
  const isDev = import.meta.env.MODE === "development";

  const isQiankun = qiankunWindow.__POWERED_BY_QIANKUN__;
  let link;
  if (isQiankun) {
    console.log('====isQiankun===',window.localStorage);
  }else{
    if (isDev) {
      if (import.meta.env.DEV) {
          link = "http://localhost:3000"
      } else {
        link = "https://192.168.29.150"
      }
    } else {
      // link = "https://cop.thinkcar.cn"
      link = "http://test1.xhinkcar.cn"
    }
    window.open(
      `https://login.dingtalk.com/oauth2/auth?redirect_uri=${link}/tcpi/index&response_type=code&client_id=ding3gxexs8wosaiun1i&scope=openid&prompt=consent`,
      "_self"
    );
  }
  
}
export function dateFormat(timestamp?: number, format = "MM/dd/yyyy"): string {
  let date: Date;
  if (timestamp) {
    if ((timestamp + "").length === 13) {
      date = new Date(timestamp);
    } else if ((timestamp + "").length === 10) {
      date = new Date(timestamp * 1000);
    } else {
      console.error("传入时间错误");
      return "-";
    }
  } else {
    date = new Date();
  }

  const o = {
    "M+": date.getMonth() + 1, // 月份
    "d+": date.getDate(), // 日
    "h+": date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
    "H+": date.getHours(), // 小时
    "m+": date.getMinutes(), // 分
    "s+": date.getSeconds(), // 秒
    "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
    a: date.getHours() < 12 ? "上午" : "下午", // 上午/下午
    A: date.getHours() < 12 ? "AM" : "PM" // AM/PM
  } as any;
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (const k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
}